package com.ricchieri.model;

import java.sql.Time;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import com.ricchieri.util.FacesUtil;

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "trip")
public class Trip extends BaseEntity {
	private static final long serialVersionUID = 2662012700912738545L;

	@OneToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "placeOrigin", nullable = false)
	private Place placeOrigin;

	@OneToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "placeDestiny", nullable = false)
	private Place placeDestiny;
	
	@Column(name = "totalKM", nullable = true)
	private double totalKM;
		
	@Column(name = "time", nullable = true)
	private Time time;

	@OneToMany(fetch = FetchType.LAZY, cascade=CascadeType.ALL)
	@JoinColumn(name = "price", nullable = false, insertable = true, updatable = true)
	private List<Price> price;

	public Place getPlaceOrigin() {
		return placeOrigin;
	}

	public void setPlaceOrigin(Place placeOrigin) {
		this.placeOrigin = placeOrigin;
	}

	public Place getPlaceDestiny() {
		return placeDestiny;
	}

	public void setPlaceDestiny(Place placeDestiny) {
		this.placeDestiny = placeDestiny;
	}
	
	public String getFormatTrip() {
		String tripDescription = FacesUtil.getMessage(
				this.getPlaceOrigin().getDescription());
		tripDescription = tripDescription.concat(" -> ");
		tripDescription = tripDescription.concat(FacesUtil.getMessage(
				this.getPlaceDestiny().getDescription()));
		
		return tripDescription;
	}

	public double getTotalKM() {
		return totalKM;
	}

	public void setTotalKM(double totalKM) {
		this.totalKM = totalKM;
	}

	public Time getTime() {
		return time;
	}

	public void setTime(Time time) {
		this.time = time;
	}

	public List<Price> getPrice() {
		return price;
	}

	public void setPrice(List<Price> price) {
		this.price = price;
	}
	
	public Price obtainPriceInPeriod(Date date) {
		for (Price price : getPrice()) {
			if(price.isDateInPeriod(date)) {
				return price;
			}
		}
		return null;
	}
}